package com.handler;

import com.util.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.List;

public class RxtxHandler  extends ChannelInboundHandlerAdapter {

    private List<String> data;

    public RxtxHandler(List<String> data) {
        this.data = data;
    }

    /**
     * 客户端接收到数据的回调
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{

        if(msg instanceof String ){
            String packet = (String)msg;
            //如果是0103 ,表示为上位机发来的请求命令
            if(InputCommandUtil.isMasterCmd(packet)){
                System.out.println("获取主机请求："+packet);
                int starAddr = InputCommandUtil.getStarAddrInt(packet);
                int dataCountInt = InputCommandUtil.getReqDataCountInt(packet);
                List<String> strings = data.subList(starAddr, starAddr + dataCountInt);

                String resCommand = OutputCommandUtil.packet(strings);

                writeAndFlush(ctx.channel(),resCommand);

            }else{
            //否则是从传感器发来的响应命令
                if(InputCommandUtil.isSlaveCmd(packet)){
                    //其它则表示从下位机取的数据
                    System.out.println("获取从机数据："+packet);

                    if(DecodeCommandUtil.isSmoking(packet)){
                        String[] val = DecodeCommandUtil.decodeSoaking(packet);
                        ListUtil.setBoolean(data,"50",val[1]);

                    }else if(DecodeCommandUtil.isSoaking(packet)){
                        String[] val = DecodeCommandUtil.decodeSoaking(packet);
                        ListUtil.setBoolean(data,"40",val[1]);
                    }
                    else if(DecodeCommandUtil.isWetTemperature(packet)){
                        String[] val = DecodeCommandUtil.decodeSWD(packet);
                        ListUtil.setFloat(data,"30",val[1]);
                        ListUtil.setFloat(data,"20",val[2]);
                    }
                }else{
                    //数据不满足传感器的数据格式
                    System.out.println("一条异常数据："+packet);
                }
            }
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    public void writeAndFlush(Channel channel,String hexString) {

        byte[] bytes = ByteUtil.hexStringToBytes(hexString);
        ByteBuf buffer = channel.alloc().buffer();
        ByteBuf byteBuf = buffer.writeBytes(bytes);
        channel.writeAndFlush(byteBuf);
    }


}
